import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;


public class SpellCheckerGUI extends JFrame implements WindowListener, ActionListener {

    private JTextField textField;
    private JLabel label;
    private JButton searchButton;
    private SpellChecker spellChecker;
    
    public SpellCheckerGUI() {
        super("Simple Dictionary");
        makeGUI();
        addWindowListener(this);
        pack();
        setSize(new Dimension(500, 400));
        setResizable(false);
        setVisible(true);
        spellChecker = new SpellChecker();
    }
    
    private void makeGUI() {
        Container c = getContentPane();
        textField = new JTextField();
        c.add(textField, "North");
        label = new JLabel();
        label.setText("Enter a new word");
        c.add(label, "South");
        searchButton = new JButton("Search");
        searchButton.addActionListener(this);
        c.add(searchButton, "East");
        
    }
    
    @Override
    public void actionPerformed(ActionEvent e) {
        String word = textField.getText();
        if (word.equals("quit")) {
            label.setText("Goodbye");
            WindowEvent we = new WindowEvent(this, EXIT_ON_CLOSE);
            windowClosed(we);
        } else {
            word = word.toLowerCase();
            SpellCheckResult result = spellChecker.check(word);
            if (result.isCorrect()) {
                label.setText(word + " is correct. Enter next word");
            } else {
                String before = result.getBefore();
                String after = result.getAfter();
                label.setText(word + " not found. Nearest neighbour(s) " + 
                        (before != null ? before + " ": "") + (after != null ? after : "" ));
            }
        }
        
    }

    @Override
    public void windowActivated(WindowEvent e) {
    }

    @Override
    public void windowClosed(WindowEvent e) {
        System.exit(0);
        
    }

    @Override
    public void windowClosing(WindowEvent e) {
        dispose();
        
    }

    @Override
    public void windowDeactivated(WindowEvent e) {
    }

    @Override
    public void windowDeiconified(WindowEvent e) {
    }

    @Override
    public void windowIconified(WindowEvent e) {
    }

    @Override
    public void windowOpened(WindowEvent e) {
    }
    
    
}
